const app = getApp();
let keys = 'SGXBZ-6X3K6-NYLSF-MALZD-QC6PK-BABOS';
// pages/homePage/HomePage.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        screenHeight: 0,
        leaseCount: 500,
        orderCount: 30000,

        address: "",
        showaddress: "",
        district: '',
        userInfo: {},
        citylist: [{ id: '431301000000', name: '娄底市直' },
            { id: '431302999000', name: '娄星区' },
            { id: '431381999000', name: '冷水江市' },
            { id: '431382999000', name: '涟源市' },
            { id: '431321999000', name: '双峰县' },
            { id: '431322999000', name: '新化县' },
            { id: '431323999000', name: '娄底市经开区' }
        ],

        weather: {
            cond_txt: '晴',
            tmp: 0,
            qlty: '优',
        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        this.setData({
            screenHeight: getApp().globalData.screenHeight
        });
        console.log("screenHeight", this.data.screenHeight);

        let _this = this;
        wx.getLocation({
            type: 'gcj02', //返回可以用于wx.openLocation的经纬度
            success(res) {
                const latitude = res.latitude
                const longitude = res.longitude
                _this.getDistrict(latitude, longitude)
            }
        })
        if (app.globalData.userInfo) {
            this.setData({
                userInfo: app.globalData.userInfo,
                hasUserInfo: true
            })
        } else if (this.data.canIUse) {
            // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
            // 所以此处加入 callback 以防止这种情况
            app.userInfoReadyCallback = res => {
                this.setData({
                    userInfo: res.userInfo,
                    hasUserInfo: true
                })
            }
        } else {
            // 在没有 open-type=getUserInfo 版本的兼容处理
            wx.getUserInfo({
                success: res => {
                    app.globalData.userInfo = res.userInfo
                    this.setData({
                        userInfo: res.userInfo,
                        hasUserInfo: true
                    })
                }
            })
        }

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        let _this = this
        wx.getStorage({
            key: 'loginData',
            success(res) {
                console.log(res)
                _this.setData({
                    loginData: res.data
                })
            },
            fail(res) {
                _this.setData({
                    loginData: ''
                })
            }
        })
        if (this.data.address != "") {
            _this.setData({
                showaddress: this.data.address.district
            })
            _this.getCityWeather(this.data.address.city)
        } else {
            wx.getSetting({
                success(res) {
                    if (res.authSetting['scope.userLocation'] === undefined) {

                    } else if (!res.authSetting['scope.userLocation']) {
                        wx.showModal({
                            title: '提示！',
                            content: "位置信息未被允许获取，请前往授权",
                            success: function(res) {
                                if (res.confirm) {
                                    wx.openSetting({
                                        success(res) {
                                            console.log(res.authSetting)
                                        }
                                    })
                                }
                            }
                        })
                    } else {
                        wx.getLocation({
                            type: 'gcj02', //返回可以用于wx.openLocation的经纬度
                            success(res) {
                                const latitude = res.latitude
                                const longitude = res.longitude
                                _this.getDistrict(latitude, longitude)
                            }
                        })
                    }
                }
            })
        }

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {

    },
    getDistrict(latitude, longitude) {
        let _this = this
        wx.request({
            url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=${keys}`,
            header: {
                'Content-Type': 'application/json'
            },
            success: function(res) {
                console.log(res.data.result.address_component.district, res.data.result)
                // 省
                let province = res.data.result.address_component.province;
                // 市
                let city = res.data.result.address_component.city;
                // 区
                let district = res.data.result.address_component.district;
                let adcode = res.data.result.ad_info.adcode
                let region_code = ''
                _this.data.citylist.map((item) => {
                    if (item.name == district) {
                        region_code = item.id
                    }
                })
                if (region_code == '') {
                    region_code = '431301000000'
                }
                wx.setStorage({
                    data: region_code,
                    key: 'regionCode',
                })
                _this.setData({
                    address: {
                        province: province,
                        city: city,
                        district: district,
                        currentCityCode: adcode,
                    },
                    showaddress: district
                })
                _this.setData({
                    district: res.data.result.address_component.district
                })
                _this.getCityWeather(city)
            }
        })
    },
    getCityWeather: function(city) {
        // https://blog.csdn.net/qq_39590763/article/details/83502192
        // https://www.qweather.com/
        // https://dev.qweather.com/
        let _this = this;
        wx.request({
            url: 'https://free-api.heweather.net/s6/weather/now',
            data: {
                location: city,
                key: "b586b23c37b14a83907b6db62e8c9c22"
            },
            success: function(res) {
                console.log("getCityWeather weather/now", res.data);
                _this.setData({
                    weather: {
                        ..._this.data.weather,
                        cond_txt: res.data.HeWeather6[0].now.cond_txt,
                        tmp: res.data.HeWeather6[0].now.tmp,
                    }
                });
                console.log("getCityWeather weather/now",{..._this.data.weather});
            }
        });
        wx.request({
            url: 'https://free-api.heweather.net/s6/air/now',
            data: {
                location: city,
                key: "b586b23c37b14a83907b6db62e8c9c22"
            },
            success: function(res) {
                console.log("getCityWeather air/now", res.data);
                _this.setData({
                    weather: {
                        ..._this.data.weather,
                        qlty: res.data.HeWeather6[0].air_now_city.qlty,
                    }
                });
                console.log("getCityWeather air/now",{..._this.data.weather});
            }
        });
    },

    onTapSummary: function(e) {
        console.log('onTapSummary', {
            e
        });
    }
})